package com.example.myapplication;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.Formatter;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    boolean dark = false;
    List<VideoInfo> listData = new ArrayList<>();
    int curItemPosition;
    private LinearLayout llTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    0);
        }
        llTitle = findViewById(R.id.llTitle);
        ImageView ivBack = findViewById(R.id.ivBack);
        ImageView ivMore = findViewById(R.id.ivMore);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ivMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopMore();
            }
        });
        RecyclerView mRecyclerView = findViewById(R.id.mRecyclerView);
        File externalStorageDirectory = Environment.getExternalStorageDirectory();
        File androidDirectory = new File(externalStorageDirectory, "Android");
        if (androidDirectory.isDirectory()){
            File[] files = androidDirectory.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return name.endsWith(".mp4");
                }
            });
            for (File file : files) {
                Log.d("VideoInfo","filePath:"+file.getAbsolutePath());
                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                try {
                    retriever.setDataSource(file.getPath());
                    String durationStr = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                    long duration = Long.parseLong(durationStr); // in milliseconds
                    String size = Formatter.formatFileSize(this,file.length());
                    Bitmap firstFrame = retriever.getFrameAtTime();
                    String name = file.getName().substring(0,file.getName().lastIndexOf("."));
                    VideoInfo videoInfo = new VideoInfo(name, firstFrame, formatDuration2HMS(duration), size,file.getAbsolutePath());
                    listData.add(videoInfo);
                } catch (Exception e) {
                } finally {
                    retriever.release();
                }
            }
        }

        VideoItemAdapter videoItemAdapter = new VideoItemAdapter(this,listData);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this,2));
        mRecyclerView.setAdapter(videoItemAdapter);
        videoItemAdapter.setOnItemClickLinstener(new VideoItemAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                curItemPosition = position;
                startPlayActivity();
            }
        });
    }

    public String formatDuration2HMS(long duration){
        long s = duration/1000;
        long min = s/60;
        long hour = min/60;

        return (hour<10 ? "0"+hour : hour)+":"+(min%60<10 ? "0"+min%60 : min%60)+":"+(s%60<10 ? "0"+s%60 : s%60);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //开启下一个
        if (resultCode == 217){
            curItemPosition = (curItemPosition + 1 < listData.size()) ? curItemPosition + 1 : 0;
            startPlayActivity();
        }
    }

    private void startPlayActivity(){
        VideoInfo videoInfo = listData.get(curItemPosition);
        Intent intent = new Intent(MainActivity.this, VideoPlayActivity.class);
        intent.putExtra("video_url",videoInfo.getFilePath());
        intent.putExtra("video_name",videoInfo.getName());
        startActivityForResult(intent,0);
    }

    public void changeTheme(){
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            return;
        }
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(dark ? Color.WHITE:Color.BLACK);
        View decor = getWindow().getDecorView();
        if (decor != null) {
            int flags = decor.getSystemUiVisibility();
            if (dark) {
                flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            } else {
                flags &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            }
            decor.setSystemUiVisibility(flags);
        }
    }

    private void showPopMore(){
        View view = LayoutInflater.from(this).inflate(R.layout.pop_video_more, null, false);
        final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x99000000));
        popupWindow.showAsDropDown(llTitle,0,10,Gravity.RIGHT);
//        popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        listData.clear();
        listData = null;
    }
}